import { constantRoutes } from '@/router'
import { getAsyncRoutes } from '@/api/role'
import Layout from '@/layout/index'
import Empty from '@/layout/Empty'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function buildRouteConfig(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.children) {
      tmp.children = buildRouteConfig(tmp.children)
    }
    if (tmp.component === 'layout/Layout') {
      tmp.component = Layout
    } else if (tmp.component === 'layout/Empty') {
      tmp.component = Empty
    } else if (tmp.component) {
      let viewPath = tmp.component
      viewPath = viewPath.replace(/^\/*views\//g, '')
      // tmp.component = () => Promise.resolve(require(`@/views/${viewPath}`).default)
      tmp.component = () => import(`@/views/${viewPath}`)
    }
    res.push(tmp)
  })
  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  topMenu: '',
  menuRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_TOP_MENU: (state, menu) => {
    state.topMenu = menu
    const topRoutes = state.routes.filter(route => {
      return route.meta && !!route.meta.isTop && route.meta.title === menu
    })
    state.menuRoutes = topRoutes.length > 0 ? topRoutes[0].children : []
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      getAsyncRoutes().then(json => {
        const accessedRoutes = buildRouteConfig(json.data)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  },
  setMenu({ commit }, menu) {
    return new Promise(resolve => {
      commit('SET_TOP_MENU', menu)
      resolve(menu)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
